#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
项目名称: 中青晶彩看点查询今日奖励
Author: Fidcz
功能: 中青晶彩看点查询今日奖励
Date: 2021/12/11 16:08
Update: 2021/12/20 21:21
cron: 0 50 22 * * ?
new Env('中青晶彩看点查询今日奖励');

    中青cookie保存为 export zq_cookies="cookie1:备注1@cookie2:备注2"   # 备注可忽略,既 "cookie1@cookie2"
    晶彩cookie为    export jc_cookies,其他同上
"""


import sys, os
import requests
import time
import logging
from datetime import datetime

# 中青晶彩今日总收益
zqAllScore = 0
jcAllScore = 0


def loadSend():
    #print("加载推送功能")
    global send
    send = None
    cur_path = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(cur_path)
    if os.path.exists(cur_path + "/sendNotify.py"):
        try:
            from sendNotify import send
        except Exception as e:
            send = None
            print("加载通知服务失败~",e)



# 使用logger输出
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

def bodyTodict(bodyString):
    """
        把body形式文本转为dict
    """

    temp_split = bodyString.split('&')

    resultDict= {}
    for data in temp_split:
        resultDict[data.split('=')[0]] = data.split('=')[1]
    
    # print(resultDict)
    return resultDict

def getCookie(pt:str='zq'):
    """
        获取中青cookie,返回list
    """
    if pt != 'zq':
        pt = 'jc'
    cookieList = []
    if f'{pt}_cookies' in os.environ:
        cookiesStr = os.environ[f"{pt}_cookies"]
        # 使用@分割每个cookie
        cookiesSplit = cookiesStr.split('@')
        for cookie in cookiesSplit:
            if ':' in cookie:
                cookieList.append([cookie.split(':')[0], cookie.split(':')[1]])
            else:
                cookieList.append([cookie.split(':')[0], ''])

    return cookieList

def getTodayScore(pt:str='zq', cookie:str=''):
    """
        获取中青晶彩今日奖励
    """
    try:
        global zqAllScore, jcAllScore

        domain = 'kandian.wkandian.com'
        scoreText = '青豆'
        if pt == 'jc':
            domain = 'ant.xunsl.com'
            scoreText = '金币'

        if cookie == '' or cookie == None:
            return []

        time1 = int(time.time())
        # uid = cookie.split('&uid=')[1]
        bodyVal = cookie.split('&uid')[0]
        cookie1 = bodyVal.replace('zqkey=', 'cookie=')
        cookie_id = cookie1.replace('zqkey_id=', 'cookie_id=')

        zq_cookie1 = f'{cookie_id}&device_brand=xfdg&device_id=cc7dgdsgfsz83e&device_model=1gx&device_platform=android&device_type=android&inner_version=202107261526&mi=0&openudid=cc7dgdsgfsz83e&os_api=27&os_version=bdftgsdfga&phone_network=WIFI&phone_sim=1&request_time={str(time1)}&time={str(time1-10)}&{bodyVal}'

        getScoreUrl = f'https://{domain}/wap/user/balance?{zq_cookie1}'
        getScoreHeader = {
            'Host': domain
        }

        getScoreData = zq_cookie1
        getScoreRespon = requests.post(url=getScoreUrl, headers=getScoreHeader, data=bodyTodict(getScoreData))
        # print(getJlRespon.text)
        # with open('test.json', 'w') as file:
        #     file.write(json.dumps(getJlRespon.json(), ensure_ascii=False))
        getScoreRespon = getScoreRespon.json()
        if int(getScoreRespon['status']) != 0:
            return [[getScoreRespon['msg']]]

        if pt == 'zq':
            zqAllScore += round(int(getScoreRespon["user"]["today_score"])/10000, 4)
        else:
            jcAllScore += round(int(getScoreRespon["user"]["today_score"])/10000, 4)

        return f'今日收益:{getScoreRespon["user"]["today_score"]}{scoreText}({round(int(getScoreRespon["user"]["today_score"])/10000, 4)}元)\n当前总计:{getScoreRespon["user"]["score"]}{scoreText}({getScoreRespon["user"]["money"]}元)'

        # for dayIndex in range(dateDay):
    except Exception as error:
        return [[f'获取出错:{repr(error)}', f'error line:{error.__traceback__.tb_lineno}']]
    


if __name__ == '__main__':
    zq_cookies = jc_cookies = []
    zq_cookies = getCookie('zq')
    jc_cookies = getCookie('jc')
    logger.info(f'提供了{len(zq_cookies)}个中青账号')
    logger.info(f'提供了{len(jc_cookies)}个晶彩账号')

    if len(zq_cookies) == 0 and len(jc_cookies) == 0:
        logger.info('\n未提供中青或晶彩cookie,结束')

    loadSend()
    sendList = []

    logger.info('\n>>>>开始获取中青今日奖励<<<<')

    for zq_cookie_index in range(len(zq_cookies)):
        todayScoreText = getTodayScore('zq', zq_cookies[zq_cookie_index][0])

        logger.info(f'\n\n>>中青账号{zq_cookie_index+1}:{zq_cookies[zq_cookie_index][1]} 今日奖励:')
        logger.info(todayScoreText)
        sendList.append(f'\n\n>>中青账号{zq_cookie_index+1}:{zq_cookies[zq_cookie_index][1]} 今日奖励:\n{todayScoreText}')
        

    logger.info('\n\n>>>>开始获取晶彩今日奖励<<<<')

    for jc_cookie_index in range(len(jc_cookies)):
        todayScoreText = getTodayScore('jc', jc_cookies[jc_cookie_index][0])

        logger.info(f'\n>>晶彩账号{jc_cookie_index+1}:{jc_cookies[jc_cookie_index][1]} 今日奖励:')
        logger.info(todayScoreText)
        sendList.append(f'\n\n>>晶彩账号{jc_cookie_index+1}:{zq_cookies[jc_cookie_index][1]} 今日奖励:\n{todayScoreText}')
    
    logger.info(f'\n\n中青总计:{zqAllScore}元\n晶彩总计:{jcAllScore}元\n全部总计:{round(zqAllScore+jcAllScore, 4)}元')

    if send:
        if len(sendList) > 0:
            sendText = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            sendText += (''.join(sendList))[1:]
            sendText += f'\n\n中青总计:{round(zqAllScore,4)}元\n晶彩总计:{round(jcAllScore,4)}元\n全部总计:{round(zqAllScore+jcAllScore, 4)}元'
            send('中青晶彩今日奖励', sendText)
    exit(1)